<!DOCTYPE html>












  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">


























<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2">

<link rel="stylesheet" href="/css/main.css?v=7.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/Peppa.png?v=7.0.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/Peppa.jpg?v=7.0.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/Peppa.jpg?v=7.0.0">








<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '7.0.0',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="康托展开与逆康托展开 1 康托展开1.1 定义康托展开是一个全排列到一个自然数的双射，常用于构建哈希表时的空间压缩。 之所以说是空间压缩,是因为当我们进行哈希运算时，如果是一个正常的长度为$n$数列，数的范围在$1 \to n$ 的情况下，这个数列总共存在的情况有$n^n$种，我们将数列映射为整数时，则至少需要$n^n$这个数量级以上的空间 而$n$的全排列很明显只有$n!$种情况，也就是说，会没">
<meta name="keywords" content="ACM,Math">
<meta property="og:type" content="article">
<meta property="og:title" content="康托展开与逆康托展开">
<meta property="og:url" content="https://linxi99.gitee.io/20190211/康托展开与逆康托展开/index.html">
<meta property="og:site_name" content="linxi&#39;s dream">
<meta property="og:description" content="康托展开与逆康托展开 1 康托展开1.1 定义康托展开是一个全排列到一个自然数的双射，常用于构建哈希表时的空间压缩。 之所以说是空间压缩,是因为当我们进行哈希运算时，如果是一个正常的长度为$n$数列，数的范围在$1 \to n$ 的情况下，这个数列总共存在的情况有$n^n$种，我们将数列映射为整数时，则至少需要$n^n$这个数量级以上的空间 而$n$的全排列很明显只有$n!$种情况，也就是说，会没">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-11-25T09:54:35.310Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="康托展开与逆康托展开">
<meta name="twitter:description" content="康托展开与逆康托展开 1 康托展开1.1 定义康托展开是一个全排列到一个自然数的双射，常用于构建哈希表时的空间压缩。 之所以说是空间压缩,是因为当我们进行哈希运算时，如果是一个正常的长度为$n$数列，数的范围在$1 \to n$ 的情况下，这个数列总共存在的情况有$n^n$种，我们将数列映射为整数时，则至少需要$n^n$这个数量级以上的空间 而$n$的全排列很明显只有$n!$种情况，也就是说，会没">






  <link rel="canonical" href="https://linxi99.gitee.io/20190211/康托展开与逆康托展开/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>康托展开与逆康托展开 | linxi's dream</title>
  






  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b4099cd89c9f33abab06a03748dac801";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>







  <noscript>
  <style>
  .use-motion .motion-element,
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-title { opacity: initial; }

  .use-motion .logo,
  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">linxi's dream</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">穷且益坚，不坠青云之志</p>
      
    
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-tags">

    
    
    
      
    

    

    <a href="/tags/" rel="section"><i class="menu-item-icon fa fa-fw fa-tags"></i> <br>标签</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-categories">

    
    
    
      
    

    

    <a href="/categories/" rel="section"><i class="menu-item-icon fa fa-fw fa-th"></i> <br>分类</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>

      
      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>搜索</a>
        </li>
      
    </ul>
  

  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
            

          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://linxi99.gitee.io/20190211/康托展开与逆康托展开/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="linxi">
      <meta itemprop="description" content="stay hungry, stay foolish">
      <meta itemprop="image" content="/images/star.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="linxi's dream">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">康托展开与逆康托展开

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-02-11 16:56:52" itemprop="dateCreated datePublished" datetime="2019-02-11T16:56:52+08:00">2019-02-11</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-11-25 17:54:35" itemprop="dateModified" datetime="2019-11-25T17:54:35+08:00">2019-11-25</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/数论只会GCD/" itemprop="url" rel="index"><span itemprop="name">数论只会GCD</span></a></span>

                
                
              
            </span>
          

          
            
            
              
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
            
                <span class="post-meta-item-text">评论数：</span>
                <a href="/20190211/康托展开与逆康托展开/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/20190211/康托展开与逆康托展开/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
            <span id="/20190211/康托展开与逆康托展开/" class="leancloud_visitors" data-flag-title="康托展开与逆康托展开">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              
                <span class="post-meta-item-text">阅读次数：</span>
              
                <span class="leancloud-visitors-count"></span>
            </span>
            <span class="post-meta-divider">|
            </span> <span title="post.wordcount">
            <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
            </span>字数： 1.8k
            </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>康托展开与逆康托展开</p>
<h1 id="1-康托展开"><a href="#1-康托展开" class="headerlink" title="1 康托展开"></a>1 康托展开</h1><h2 id="1-1-定义"><a href="#1-1-定义" class="headerlink" title="1.1 定义"></a>1.1 定义</h2><p>康托展开是一个全排列到一个自然数的双射，常用于构建哈希表时的空间压缩。</p>
<p>之所以说是空间压缩,是因为当我们进行哈希运算时，如果是一个正常的长度为$n$数列，数的范围在$1 \to n$ 的情况下，这个数列总共存在的情况有$n^n$种，我们将数列映射为整数时，则至少需要$n^n$这个数量级以上的空间</p>
<p>而$n$的全排列很明显只有$n!$种情况，也就是说，会没有必要的浪费很多空间，如何将空间降低呢，我们就需要用到康托展开与逆康托展开</p>
<p>举个例子，当$n == 9$时，普通哈希算法需要的空间为$9 ^ 9 = 387420489$，而康托展开只需要$9! = 3682880$的空间即可</p>
<p> 康托展开的实质是计算当前排列在所有由小到大全排列中的顺序，因此是可逆的。</p>
<a id="more"></a>
<h2 id="1-2-康托展开运算"><a href="#1-2-康托展开运算" class="headerlink" title="1.2 康托展开运算"></a>1.2 康托展开运算</h2><script type="math/tex; mode=display">X = a_n(n - 1)! + a_{n - 1}(n - 2)! + \cdots + a_1\times 0!</script><p>其中$a_i$为$0 \le a_i &lt; i$的非负整数，$1 \le i \le n$</p>
<p>$a_i$ 表示原数的第$i$位在当前未出现的元素中是排在第几个（也可以理解为位置$i$后面的数有多少个是小于第$i$位的数）</p>
<h2 id="1-3-举个例子"><a href="#1-3-举个例子" class="headerlink" title="1.3 举个例子"></a>1.3 举个例子</h2><p>在$(1, 2, 3, 4)$的全排列中，我们计算排列 $(2, 4, 1, 3)$是第几小的排列</p>
<p>此时我们可以发现 2 后面只有一个比它小的数</p>
<p>所以$a_4 = 1$，同理$a_3 = 2, a_2 = 0, a_1 = 0$ </p>
<p>代入公式则可以计算出此时</p>
<script type="math/tex; mode=display">X = 1 \times 3! + 2 \times 2! + 0 \times 1! + 0 \times 0! = 10</script><p>所以有10个排列比该排列小，该排列的次序应为11</p>
<h2 id="1-4-实现技巧"><a href="#1-4-实现技巧" class="headerlink" title="1.4 实现技巧"></a>1.4 实现技巧</h2><p>统计当前未出现的元素的排的名次时，我们可以采用不同的方式</p>
<p>当$n$很小是，我们可以按顺序暴力遍历所有元素，查看是否出现，统计其名次</p>
<p>当$n$比较大时，我们可以考虑通过线段树来查询</p>
<h1 id="2-逆康托展开"><a href="#2-逆康托展开" class="headerlink" title="2 逆康托展开"></a>2 逆康托展开</h1><p>既然康托展开是一个全排列到一个自然数的双射，那么我们一定可以通过它的名次，来确定它的具体排列情况。</p>
<p>假设我们想知道$5$的全排列中的第$34$小的排列</p>
<p>我们知道，有$33$个排列小于它。我们便可以通过上述运算过程的逆过程推出该排列的具体内容</p>
<script type="math/tex; mode=display">34 \div 4! = 1 \cdots 10</script><p>因此$a_5 = 1$即未出现的数字中有一个小于它，即它是$2$</p>
<script type="math/tex; mode=display">10 \div 3! = 1 \cdots 4</script><p>因此$a_4 = 1$即未出现的数字中有一个小于它，即它是$3$</p>
<script type="math/tex; mode=display">4 \div 2! = 2 \cdots 0</script><p>因此$a_3 = 2$即未出现的数字中有两个小于它，即它是$5$</p>
<script type="math/tex; mode=display">0 \div 1! = 0 \cdots 0</script><p>因此$a_2 = 0$即未出现的数字中有零个小于它，即它是$1$</p>
<p>最后一位显然是 $4$</p>
<p>因此该排列为 $(2, 3, 5, 1, 4)$</p>
<h1 id="3-代码实现"><a href="#3-代码实现" class="headerlink" title="3 代码实现"></a>3 代码实现</h1><figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">int</span> a[<span class="number">12</span>], fac[<span class="number">12</span>];</span><br><span class="line"><span class="keyword">bool</span> vis[<span class="number">12</span>];</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">getfac</span><span class="params">(<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    fac[<span class="number">0</span>] = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; ++i) fac[i] = fac[i - <span class="number">1</span>]*i;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">cantor</span><span class="params">(<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; ++i)&#123;</span><br><span class="line">        <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j = i + <span class="number">1</span>; j &lt; n; ++j) <span class="keyword">if</span>(a[i] &gt; a[j]) ++cnt;</span><br><span class="line">        ret += cnt*fac[n - <span class="number">1</span> - i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">decantor</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; ++i) vis[i] = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">int</span> tot = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = n; i &gt;= <span class="number">1</span>; --i)&#123;</span><br><span class="line">        <span class="keyword">int</span> q = x/fac[i - <span class="number">1</span>];</span><br><span class="line">        <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= n; ++j)&#123;</span><br><span class="line">            <span class="keyword">if</span>(vis[j]) <span class="keyword">continue</span>;</span><br><span class="line">            <span class="keyword">if</span>(++cnt &gt; q)&#123;</span><br><span class="line">                a[tot++] = j;</span><br><span class="line">                vis[j] = <span class="literal">true</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        x = x%fac[i - <span class="number">1</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h1 id="4-应用价值"><a href="#4-应用价值" class="headerlink" title="4 应用价值"></a>4 应用价值</h1><h2 id="4-1-快速确定某排列的名次"><a href="#4-1-快速确定某排列的名次" class="headerlink" title="4.1 快速确定某排列的名次"></a>4.1 快速确定某排列的名次</h2><h2 id="4-2-知道名次快速确定排列的内容"><a href="#4-2-知道名次快速确定排列的内容" class="headerlink" title="4.2 知道名次快速确定排列的内容"></a>4.2 知道名次快速确定排列的内容</h2><h2 id="4-3-压缩哈希空间减低空间复杂度"><a href="#4-3-压缩哈希空间减低空间复杂度" class="headerlink" title="4.3 压缩哈希空间减低空间复杂度"></a>4.3 压缩哈希空间减低空间复杂度</h2><h1 id="5-经典例题（八数码）"><a href="#5-经典例题（八数码）" class="headerlink" title="5 经典例题（八数码）"></a>5 经典例题（八数码）</h1><p>其中经典例题</p>
<p>hdu1043 Eight 八数码</p>
<p>给定一个现有的九宫格布局，请输出将它移动至初始状态的移动方法的步骤</p>
<p>便是利用康托展开加bfs解决的</p>
<figure class="highlight cpp"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* ***********************************************</span></span><br><span class="line"><span class="comment">Author        :linxi</span></span><br><span class="line"><span class="comment">Created Time  :2019年02月09日 星期六 10时58分59秒</span></span><br><span class="line"><span class="comment">File Name     :1.cpp</span></span><br><span class="line"><span class="comment">************************************************ */</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;iostream&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cstdio&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cstring&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;algorithm&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;string&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cmath&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;cstdlib&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;vector&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;queue&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;set&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;map&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span> <span class="meta-string">&lt;bits/stdc++.h&gt;</span></span></span><br><span class="line"><span class="keyword">using</span> <span class="keyword">namespace</span> <span class="built_in">std</span>;</span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sd(n) scanf(<span class="meta-string">"%d"</span>,&amp;n)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sdd(n,m) scanf(<span class="meta-string">"%d%d"</span>,&amp;n,&amp;m)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sddd(n,m,k) scanf(<span class="meta-string">"%d%d%d"</span>,&amp;n,&amp;m,&amp;k)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> pd(n) printf(<span class="meta-string">"%d\n"</span>, (n))</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> pdd(n,m) printf(<span class="meta-string">"%d %d"</span>, n, m)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> pld(n) printf(<span class="meta-string">"%lld\n"</span>, n)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> pldd(n,m) printf(<span class="meta-string">"%lld %lld\n"</span>, n, m)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sld(n) scanf(<span class="meta-string">"%lld"</span>,&amp;n)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sldd(n,m) scanf(<span class="meta-string">"%lld%lld"</span>,&amp;n,&amp;m)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> slddd(n,m,k) scanf(<span class="meta-string">"%lld%lld%lld"</span>,&amp;n,&amp;m,&amp;k)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sf(n) scanf(<span class="meta-string">"%lf"</span>,&amp;n)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sff(n,m) scanf(<span class="meta-string">"%lf%lf"</span>,&amp;n,&amp;m)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> sfff(n,m,k) scanf(<span class="meta-string">"%lf%lf%lf"</span>,&amp;n,&amp;m,&amp;k)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> ss(str) scanf(<span class="meta-string">"%s"</span>,str)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> rep(i,a,n) for (int i=a;i&lt;n;i++)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> per(i,a,n) for (int i=n-1;i&gt;=a;i--)</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> mm(a,n) memset(a, n, sizeof(a))</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> debug(x) cout&lt;&lt;#x&lt;&lt;<span class="meta-string">": "</span>&lt;&lt;x&lt;&lt;endl</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> pb push_back</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> all(x) (x).begin(),(x).end()</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> fi first</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> se second</span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">define</span> mp make_pair()</span></span><br><span class="line"><span class="keyword">typedef</span> pair&lt;<span class="keyword">int</span>,<span class="keyword">int</span>&gt; PII;</span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">long</span> <span class="keyword">long</span> ll;</span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">unsigned</span> <span class="keyword">long</span> <span class="keyword">long</span> ull;</span><br><span class="line"><span class="keyword">typedef</span> <span class="keyword">long</span> <span class="keyword">double</span> ld;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> mod = <span class="number">1e9</span> + <span class="number">7</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">double</span> eps = <span class="number">1e-9</span>;</span><br><span class="line"><span class="keyword">const</span> <span class="keyword">int</span> maxn = <span class="number">4e5</span> + <span class="number">5</span>;</span><br><span class="line"><span class="comment">//head</span></span><br><span class="line"><span class="keyword">int</span> pre[maxn];</span><br><span class="line"><span class="keyword">char</span> dir[maxn];</span><br><span class="line"><span class="keyword">int</span> tox[] = &#123;<span class="number">0</span>, <span class="number">0</span>, <span class="number">1</span>, <span class="number">-1</span>&#125;;</span><br><span class="line"><span class="keyword">int</span> toy[] = &#123;<span class="number">1</span>, <span class="number">-1</span>, <span class="number">0</span>, <span class="number">0</span>&#125;;</span><br><span class="line"><span class="keyword">char</span> cdir[] = &#123;<span class="string">'l'</span>, <span class="string">'r'</span>, <span class="string">'u'</span>, <span class="string">'d'</span>&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">int</span> a[<span class="number">12</span>], fac[<span class="number">12</span>];</span><br><span class="line"><span class="keyword">bool</span> vis[<span class="number">12</span>];</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">getfac</span><span class="params">(<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    fac[<span class="number">0</span>] = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; n; ++i) fac[i] = fac[i - <span class="number">1</span>]*i;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">cantor</span><span class="params">(<span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">int</span> ret = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; n; ++i)&#123;</span><br><span class="line">        <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j = i + <span class="number">1</span>; j &lt; n; ++j) <span class="keyword">if</span>(a[i] &gt; a[j]) ++cnt;</span><br><span class="line">        ret += cnt*fac[n - <span class="number">1</span> - i];</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> ret;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">decantor</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> n)</span></span>&#123;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = <span class="number">1</span>; i &lt;= n; ++i) vis[i] = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">int</span> tot = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i = n; i &gt;= <span class="number">1</span>; --i)&#123;</span><br><span class="line">        <span class="keyword">int</span> q = x/fac[i - <span class="number">1</span>];</span><br><span class="line">        <span class="keyword">int</span> cnt = <span class="number">0</span>;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> j = <span class="number">1</span>; j &lt;= n; ++j)&#123;</span><br><span class="line">            <span class="keyword">if</span>(vis[j]) <span class="keyword">continue</span>;</span><br><span class="line">            <span class="keyword">if</span>(++cnt &gt; q)&#123;</span><br><span class="line">                a[tot++] = j;</span><br><span class="line">                vis[j] = <span class="literal">true</span>;</span><br><span class="line">                <span class="keyword">break</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        x = x%fac[i - <span class="number">1</span>];</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">bool</span> <span class="title">judge</span><span class="params">(<span class="keyword">int</span> x, <span class="keyword">int</span> y)</span></span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(x &lt; <span class="number">0</span> || x &gt;= <span class="number">3</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">if</span>(y &lt; <span class="number">0</span> || y &gt;= <span class="number">3</span>) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">bfs</span><span class="params">()</span></span>&#123;</span><br><span class="line">    rep(i, <span class="number">0</span>, <span class="number">9</span>) a[i] = i + <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">int</span> s = cantor(<span class="number">9</span>);</span><br><span class="line">    <span class="built_in">queue</span>&lt;<span class="keyword">int</span>&gt; qs;</span><br><span class="line">    qs.push(s);</span><br><span class="line">    pre[s] = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span>(!qs.empty())&#123;</span><br><span class="line">        s = qs.front(), qs.pop();</span><br><span class="line"><span class="comment">//        pd(s);</span></span><br><span class="line">        decantor(s, <span class="number">9</span>);</span><br><span class="line">        <span class="keyword">int</span> x = <span class="number">-1</span>, y = <span class="number">-1</span>;</span><br><span class="line">        rep(i, <span class="number">0</span>, <span class="number">9</span>)&#123;</span><br><span class="line">            <span class="keyword">if</span>(a[i] != <span class="number">9</span>) <span class="keyword">continue</span>;</span><br><span class="line">            x = i/<span class="number">3</span>, y = i%<span class="number">3</span>;</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        rep(i, <span class="number">0</span>, <span class="number">4</span>)&#123;</span><br><span class="line">            <span class="keyword">int</span> xx = x + tox[i], yy = y + toy[i];</span><br><span class="line">            <span class="keyword">if</span>(!judge(xx, yy)) <span class="keyword">continue</span>;</span><br><span class="line">            swap(a[x*<span class="number">3</span> + y], a[xx*<span class="number">3</span> + yy]);</span><br><span class="line">            <span class="keyword">int</span> ss = cantor(<span class="number">9</span>);</span><br><span class="line">            <span class="keyword">if</span>(pre[ss] == <span class="number">-1</span>)&#123;</span><br><span class="line">                qs.push(ss);</span><br><span class="line">                pre[ss] = s;</span><br><span class="line">                dir[ss] = cdir[i];</span><br><span class="line">            &#125;</span><br><span class="line">            swap(a[x*<span class="number">3</span> + y], a[xx*<span class="number">3</span> + yy]);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">char</span> s[maxn];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">int</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">	<span class="comment">//freopen("in.txt","r",stdin);</span></span><br><span class="line">	<span class="comment">//freopen("out.txt","w",stdout);</span></span><br><span class="line">    mm(pre, <span class="number">-1</span>);</span><br><span class="line">    getfac(<span class="number">9</span>);</span><br><span class="line">    bfs();</span><br><span class="line">    <span class="keyword">while</span>(ss(s) != EOF)&#123;</span><br><span class="line">        <span class="keyword">if</span>(s[<span class="number">0</span>] == <span class="string">'x'</span>) s[<span class="number">0</span>] = <span class="string">'9'</span>;</span><br><span class="line">        a[<span class="number">0</span>] = s[<span class="number">0</span>] - <span class="string">'0'</span>;</span><br><span class="line">        rep(i, <span class="number">1</span>, <span class="number">9</span>)&#123;</span><br><span class="line">            ss(s);</span><br><span class="line">            <span class="keyword">if</span>(s[<span class="number">0</span>] == <span class="string">'x'</span>) s[<span class="number">0</span>] = <span class="string">'9'</span>;</span><br><span class="line">            a[i] = s[<span class="number">0</span>] - <span class="string">'0'</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">int</span> s = cantor(<span class="number">9</span>);</span><br><span class="line">        <span class="keyword">if</span>(pre[s] == <span class="number">-1</span>)&#123;</span><br><span class="line">            <span class="built_in">puts</span>(<span class="string">"unsolvable"</span>);</span><br><span class="line">            <span class="keyword">continue</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">while</span>(s != <span class="number">0</span>)&#123;</span><br><span class="line">            <span class="built_in">printf</span>(<span class="string">"%c"</span>, dir[s]);</span><br><span class="line">            s = pre[s];</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="built_in">puts</span>(<span class="string">""</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ACM/" rel="tag"># ACM</a>
          
            <a href="/tags/Math/" rel="tag"># Math</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/20190211/ACM动态规划基础篇/" rel="next" title="ACM动态规划基础篇">
                <i class="fa fa-chevron-left"></i> ACM动态规划基础篇
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/20190211/ACM几何基础篇/" rel="prev" title="ACM几何基础篇">
                ACM几何基础篇 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  
    <div class="comments" id="comments">
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/star.jpg" alt="linxi">
            
              <p class="site-author-name" itemprop="name">linxi</p>
              <p class="site-description motion-element" itemprop="description">stay hungry, stay foolish</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">15</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">9</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">13</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          

          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://blog.csdn.net/linxilinxilinxi" title="https://blog.csdn.net/linxilinxilinxi" rel="noopener" target="_blank">My CSDN</a>
                  </li>
                
              </ul>
            </div>
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
            
            
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-康托展开"><span class="nav-number">1.</span> <span class="nav-text">1 康托展开</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-定义"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-康托展开运算"><span class="nav-number">1.2.</span> <span class="nav-text">1.2 康托展开运算</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-举个例子"><span class="nav-number">1.3.</span> <span class="nav-text">1.3 举个例子</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-4-实现技巧"><span class="nav-number">1.4.</span> <span class="nav-text">1.4 实现技巧</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-逆康托展开"><span class="nav-number">2.</span> <span class="nav-text">2 逆康托展开</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-代码实现"><span class="nav-number">3.</span> <span class="nav-text">3 代码实现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-应用价值"><span class="nav-number">4.</span> <span class="nav-text">4 应用价值</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#4-1-快速确定某排列的名次"><span class="nav-number">4.1.</span> <span class="nav-text">4.1 快速确定某排列的名次</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-2-知道名次快速确定排列的内容"><span class="nav-number">4.2.</span> <span class="nav-text">4.2 知道名次快速确定排列的内容</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-3-压缩哈希空间减低空间复杂度"><span class="nav-number">4.3.</span> <span class="nav-text">4.3 压缩哈希空间减低空间复杂度</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-经典例题（八数码）"><span class="nav-number">5.</span> <span class="nav-text">5 经典例题（八数码）</span></a></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2019 – <span itemprop="copyrightYear">2020</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">linxi</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Pisces</a> v7.0.0</div>





<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">全站共 65.5k 字</span>
</div>

        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>














  
    
    
  
  <script color="25,202,173" opacity="0.8" zindex="-1" count="200" src="/lib/canvas-nest/canvas-nest.min.js"></script>













  
  <script src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>


  


  <script src="/js/src/utils.js?v=7.0.0"></script>

  <script src="/js/src/motion.js?v=7.0.0"></script>



  
  


  <script src="/js/src/affix.js?v=7.0.0"></script>

  <script src="/js/src/schemes/pisces.js?v=7.0.0"></script>



  
  <script src="/js/src/scrollspy.js?v=7.0.0"></script>
<script src="/js/src/post-details.js?v=7.0.0"></script>



  


  <script src="/js/src/bootstrap.js?v=7.0.0"></script>



  
  

<script src="//cdn1.lncld.net/static/js/3.11.1/av-min.js"></script>



<script src="//unpkg.com/valine/dist/Valine.min.js"></script>

<script>
  var GUEST = ['nick', 'mail', 'link'];
  var guest = 'nick,mail,link';
  guest = guest.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#comments',
    verify: false,
    notify: false,
    appId: 'LwzdQrGG81bUwkUkAfdPexj1-gzGzoHsz',
    appKey: 'akTaTqH7XeeKc6CPRfB7vbDl',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: guest,
    pageSize: '10' || 10,
    visitor: false
  });
</script>




  


  
  <script>
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url).replace(/\/{2,}/g, '/');
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x"></i></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x"></i></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  
  
  <script>
    
    function addCount(Counter) {
      var $visitors = $('.leancloud_visitors');
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();

      Counter('get', '/classes/Counter', { where: JSON.stringify({ url }) })
        .done(function({ results }) {
          if (results.length > 0) {
            var counter = results[0];
            
            Counter('put', '/classes/Counter/' + counter.objectId, JSON.stringify({ time: { '__op': 'Increment', 'amount': 1 } }))
            
              .done(function() {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.time + 1);
              })
            
              .fail(function ({ responseJSON }) {
                console.log(`Failed to save Visitor num, with error message: ${responseJSON.error}`);
              })
          } else {
            
              Counter('post', '/classes/Counter', JSON.stringify({ title: title, url: url, time: 1 }))
                .done(function() {
                  var $element = $(document.getElementById(url));
                  $element.find('.leancloud-visitors-count').text(1);
                })
                .fail(function() {
                  console.log('Failed to create');
                });
            
          }
        })
        .fail(function ({ responseJSON }) {
          console.log(`LeanCloud Counter Error: ${responseJSON.code} ${responseJSON.error}`);
        });
    }
    

    $(function() {
      $.get('https://app-router.leancloud.cn/2/route?appId=' + 'LwzdQrGG81bUwkUkAfdPexj1-gzGzoHsz')
        .done(function({ api_server }) {
          var Counter = function(method, url, data) {
            return $.ajax({
              method: method,
              url: 'https://' + api_server + '/1.1' + url,
              headers: {
                'X-LC-Id': 'LwzdQrGG81bUwkUkAfdPexj1-gzGzoHsz',
                'X-LC-Key': 'akTaTqH7XeeKc6CPRfB7vbDl',
                'Content-Type': 'application/json',
              },
              data: data
            });
          };
          
            addCount(Counter);
          
        });
    });
  </script>



  

  
  

  
  

  
    
      <script type="text/x-mathjax-config">
  

  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true,
      skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
    },
    TeX: {
      
      equationNumbers: {
        autoNumber: "AMS"
      }
    }
  });
</script>

<script type="text/x-mathjax-config">
  MathJax.Hub.Queue(function() {
    var all = MathJax.Hub.getAllJax(), i;
      for (i = 0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>
<script src="//cdn.jsdelivr.net/npm/mathjax@2.7.1/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>

<style>
.MathJax_Display {
  overflow: auto hidden;
}
</style>

    
  


  

  

  

  

  

  

  

  

  

  

</body>
</html>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/clicklove.js"></script>

